/**
 * 
 */
package dk.itu.mobile.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.InputMismatchException;
import java.util.Scanner;

import dk.itu.mobile.util.CryptoBaws;

/**
 * @author group-02
 * TaskClient sends request to TaskServer using UDP protocol
 *
 */
public class TaskClient {
	private static InetAddress address;
	private static DatagramSocket socket;
	private static DatagramPacket packet;
	private static byte[] sendBuffer;
	private static byte[] recieveBuffer;
	private static String clientName;
	private static String clientPass;
	private static String tokenSecret = "tokenClientSecre";
	private static String credentials;

	public TaskClient(String name){

		try {
			address = InetAddress.getLocalHost();
		} catch( UnknownHostException ukhe) {
			ukhe.printStackTrace();
		}	
		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {


		try {
			address = InetAddress.getLocalHost();
		} catch( UnknownHostException ukhe) {
			ukhe.printStackTrace();
		}       
		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}

		// ask for username and password
		inputUserData();

		// get credentials
		getCredentials();


		while(true) {

			// ask user for request
			String action = startTerminalInput();

			sendBuffer = (credentials.trim() + "," + action.trim()).getBytes();

			packet = new DatagramPacket(sendBuffer, sendBuffer.length, address, 4445);
			try {
				socket.send(packet);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println("Sending request: " + action);

			// listen for result from server
			String serverResponse = listen();
			System.out.println(serverResponse);

			if (serverResponse.trim().equalsIgnoreCase("Time limit expired")) {
				
				// Renew user login and credentials
				inputUserData();
				getCredentials();

			};

		}

	}

	private static String startTerminalInput() {

		int action = 0;
		while(action <1 || action > 5) {
			System.out.println("Welcome "+clientName+"!");
			System.out.println("Please select the task you wish to perform:");
			System.out.println("Submit assignment  01 - press 1");
			System.out.println("Review assignment  01 - press 2");
			System.out.println("Approve assignment 01 - press 3");
			System.out.println("Reject assignment  01 - press 4");
			System.out.println("Qualify for exam -      press 5");
			System.out.println("followed by [Return]");
			try {
				action = readInteger();
			}catch (InputMismatchException ime) {
				System.out.println("Invalid character input");
				System.out.println("Please select a number between 1 & 5");
			}
		}
		String userTask = "";
		switch (action) {
		case 1:
			userTask = "handin-01"; 
			break;
		case 2:
			userTask = "review-01";
			break;
		case 3: 
			userTask = "approve-01";
			break;
		case 4: 
			userTask = "reject-01";;
			break;
		case 5: 
			userTask = "qualify-for-exam";
			break;
		}

		return userTask;

	}

	private static void inputUserData() {

		System.out.println("Please input user name, followed by [Return]");
		try {

			clientName = readString();

		}catch(IOException exception) {
			System.err.println(exception.toString());
			System.out.println("This did not go well. Please try again");
		}

		System.out.println("Please input password, followed by [Return]");
		try {
			clientPass = readString();

		}catch(IOException exception) {
			System.err.println(exception.toString());
			System.out.println("This did not go well. Please try again");
		}

	}

	private static void getCredentials() {

		// Credentials for Tokenserver
		credentials = clientName + "," + clientPass;

		try {
			sendBuffer = (CryptoBaws.encode(credentials, tokenSecret)).getBytes();
			packet = new DatagramPacket(sendBuffer, sendBuffer.length, address, 4446);
			socket.send(packet);

			System.out.println("Sending request for credentials to tokenServer");

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// Wait for message from TokenServer

		credentials = listen();

		System.out.println("Credentials received from tokenServer");

	}

	private static String readString() throws IOException {
		InputStreamReader inputStream = new InputStreamReader(System.in);
		BufferedReader inputReader = new BufferedReader(inputStream);
		return inputReader.readLine();
	}

	private static int readInteger() throws InputMismatchException{
		Scanner menuScanner = new Scanner(System.in);
		return menuScanner.nextInt();
	}

	private static String listen() {
		recieveBuffer = new byte[256];
		packet = new DatagramPacket(recieveBuffer, recieveBuffer.length);
		try {
			socket.receive(packet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String recievedMessage  = new String(packet.getData());
		return recievedMessage;
	}
}
